// console.log("numIslands.js");

let grid = [
  ["1", "1", "1", "1", "0"],
  ["1", "1", "0", "1", "0"],
  ["1", "1", "0", "0", "0"],
  ["0", "0", "0", "0", "0"],
];

let numIslands = function (grid) {
    if(!grid || grid.length === 0) return 0
    const rows = grid.length
    const cols = grid[0].length
    let islandCount = 0;
    //深度优先搜索
    function dfs(r, c){
        if (r < 0 || r > rows || c < 0 || c > cols || grid[r][c] == '0') {
            return;
        }
        // 标记为已访问
        grid[r][c] = '0';
        // 搜索上下左右四个方向
        dfs(r + 1, c)
        dfs(r - 1, c)
        dfs(r, c + 1)
        dfs(r, c - 1)
    }
    // 遍历网格
    for(let i = 0; i < rows; i++){
        for(let j = 0; j < cols; j++){
            if(grid[i][j] == '1'){
                // 发现一个岛屿
                islandCount++;
                // 深度优先搜索，标记整个岛屿
                dfs(i, j);
            }
        }
    }

    return islandCount;
};
console.log(numIslands(grid))